/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package http.rpc;

import jas.http.request.HttpRequest;
import jas.http.response.HttpResponse;
import jas.http.response.HttpResponseFactory;
import java.lang.reflect.InvocationTargetException;

/**
 *
 * @author Asger
 */
public class RpcHttpResponseFactory implements HttpResponseFactory {
    
    private RpcHttpFormatter formatter;
    private RpcListener listener;
    
    public RpcHttpResponseFactory(RpcListener listener, RpcHttpFormatter formatter) {
        this.listener = listener;
        this.formatter = formatter;
    }
    
    public HttpResponse createResponse(HttpRequest request) {
        RpcRequest rpc = formatter.parseRequest(request);
        
        try {
            Object returnValue = listener.call(rpc);
            return formatter.writeResponse(returnValue);
        } catch (NoSuchMethodException ex) {
            return formatter.writeException(ex);
        } catch (InvocationTargetException ex) {
            return formatter.writeException(ex);
        } catch (NonRemoteMethodException ex) {
            return formatter.writeException(ex);
        }
    }
    
}
